package classconverstation.cscl.ist.psu.edu.client;


import java.util.Date;

import classconverstation.cscl.ist.psu.edu.client.messengers.User;
import classconverstation.cscl.ist.psu.edu.client.services.LoginService;
import classconverstation.cscl.ist.psu.edu.client.services.LoginServiceAsync;

import com.allen_sauer.gwt.log.client.Log;
import com.google.code.p.gwtchismes.client.GWTCBox;
import com.google.code.p.gwtchismes.client.GWTCPopupBox;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.EventListener;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CaptionPanel;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.HorizontalSplitPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.VerticalSplitPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class CCForum implements EntryPoint {
    Timer repeatPostLoader = new Timer() {
        public void run() {
            loadPosts(discussion_id);
        }
    };
//  int i = 11;
//  int ii = 11;
    static private int USER_SCREEN_WIDTH = -1;
    static private int USER_SCREEN_HEIGHT = -1;
    int status_bar_height = -1;
    int canvas_menu_height = -1;
    int icon_width = -1;
    int icon_height = -1;    
    Grid file_list_hpanel;
    int row_, column_;
    
    int open_commentpanel_counter = 0;
    
    String angel_icon = GWT.getModuleBaseURL() + "../images/Angel.gif";
    String switch_icon = GWT.getModuleBaseURL() + "../images/Switch.gif";
    String home_icon = GWT.getModuleBaseURL() + "../images/Home.gif";
    String question_mark_icon = GWT.getModuleBaseURL() + "../images/question_mark.gif";
    String organization_icon = GWT.getModuleBaseURL() + "../images/organization.gif";
    String box_other_stuff_icon = GWT.getModuleBaseURL() + "../images/box_other_stuff.gif";
    String thumb_up_down_icon = GWT.getModuleBaseURL() + "../images/thumbs_up_down.gif";
    String box_paper_icon = GWT.getModuleBaseURL() + "../images/box_paper.gif";
    String script_editing_icon = GWT.getModuleBaseURL() + "../images/script-edit.gif";
    String file_help_icon = GWT.getModuleBaseURL() + "../images/file_help.gif";
    String class_commons_icon = GWT.getModuleBaseURL() + "../images/message_board.jpeg";
    String script_deleting_icon = GWT.getModuleBaseURL() + "../images/script-delete.gif";
    String label_edit_icon = GWT.getModuleBaseURL() + "../images/label-edit.gif";
    String devil_icon = GWT.getModuleBaseURL() + "../images/Devil.gif";
    String balance_icon = GWT.getModuleBaseURL() + "../images/Balance.gif";
    String recycle_icon = GWT.getModuleBaseURL() + "../images/recycle.gif";
    String folder_icon = GWT.getModuleBaseURL() + "../images/folder_icon_forum.gif";
    String text_doc_icon = GWT.getModuleBaseURL() + "../images/doc-add-icon.png";
    String upload_doc_icon = GWT.getModuleBaseURL() + "../images/upload_forum.gif";
    String contact_icon = GWT.getModuleBaseURL() + "../images/contact-icon.png";
    String configuration_forum_icon = GWT.getModuleBaseURL() + "../images/configuration_forum.gif";
    String logout_icon = GWT.getModuleBaseURL() + "../images/session_logout.gif";
    String toogle_dicussion_icon = GWT.getModuleBaseURL() + "../images/toggle_icon1.gif";
    String class_selection_icon = GWT.getModuleBaseURL() + "../images/icon-classroom.png";
    String editor_icon = GWT.getModuleBaseURL() + "../images/script-edit.gif";
    String topic_icon = GWT.getModuleBaseURL() + "../images/doc_icon_forum.gif";
    String toggle_vert = GWT.getModuleBaseURL() + "../images/toggle_vertical.png";
    String closing_icon = GWT.getModuleBaseURL() + "../images/DeleteRed.png";
    String cls_home_url = null;
    
    
    HorizontalSplitPanel hsplitpanel = new HorizontalSplitPanel();
    VerticalPanel right_panel = new VerticalPanel();
    VerticalPanel left_panel = new VerticalPanel();
    private HorizontalPanel menu_bar = new HorizontalPanel();
    private HorizontalPanel object_viewer_menu_panel = new HorizontalPanel();
    private VerticalSplitPanel anchor_viewer = new VerticalSplitPanel();
    
    private VerticalPanel anchor_description = new VerticalPanel();
    private VerticalPanel anchor_file;

    VerticalPanel forum_list_panel = new VerticalPanel();
    VerticalPanel new_discussion_list_panel = new VerticalPanel();
    
    String forum_id;
    String tmpstr;
    String discussion_id;
    String cls_id;
    String cname;
    String edit = "false";
    Label forum_name;
    String loggin;
    String recorded_hash = "";
//  String open_item_id = "";
    String user_id = "";
    String open_id = "";
    User user;
    
    VerticalPanel highlighted_doc_icon = null;
    
    ListBox file_sorting_list_box = new ListBox(false);

    ListBox forum_list = new ListBox(false);

    boolean comment_loaded = false;
    VerticalPanel new_post_vpanel = new VerticalPanel();
    VerticalPanel posts_vpanel = new VerticalPanel();
    private VerticalPanel discussion_vpanel = new VerticalPanel();
//    private VerticalPanel post_list_vpanel = new VerticalPanel();
    
    HorizontalPanel text_box_hpanel;
    
    private LoginServiceAsync loginServiceSvc = GWT.create(LoginService.class);
    
    public void onModuleLoad() {
        init();
        cls_id = Window.Location.getParameter("cls");
        cname = Window.Location.getParameter("cname");
        loginFromSession();
    }
    
    private void init() {
        String tmp = Window.Location.getHref();
        cls_home_url = Window.Location.getHref().substring(0, tmp.indexOf('#'));
        USER_SCREEN_WIDTH = Integer.valueOf(getScreenWidth());
        USER_SCREEN_HEIGHT = Integer.valueOf(getScreenHeight());
        
        if (USER_SCREEN_HEIGHT < 800) {
            icon_width = 32;
            icon_height = 32;
            canvas_menu_height = 1;
            status_bar_height = 32;
        }
        else if (USER_SCREEN_HEIGHT > 800) {
            canvas_menu_height = 34;
            icon_width = 32;
            icon_height = 32;
            status_bar_height = 64;
        }
        
        column_ = (int)((Window.getClientWidth() * 0.3)/80) - 1;
        row_ = (int)(Window.getClientWidth() / 70);
        file_list_hpanel = new Grid(row_, column_);
        comment_loaded = true;
    }
    
    private void postLogin() {
        initNewPostPanel();
        initObjectViewerMenuBar();
        if ((tmpstr = Window.Location.getHash()).trim().length() > 0) {
            file_sorting_list_box.addItem("By time descending", "time desc");
            file_sorting_list_box.addItem("By time ascending", "time asc"); 
            file_sorting_list_box.addItem("By title (A - Z)", "content desc");
            file_sorting_list_box.addItem("By title (Z - A)", "content asc");
            
            file_sorting_list_box.addChangeHandler(new ChangeHandler() {
				public void onChange(ChangeEvent event) {
					ListBox listBox = (ListBox)event.getSource();
					int selectedIndex = listBox.getSelectedIndex();
					  if (selectedIndex > 0)
					   Window.alert("Something got selected " + listBox.getValue(selectedIndex));
					   feedDocs(forum_id, "time desc");
				}
			});
            
            tmpstr = tmpstr.substring(1);
            String[] trmps = tmpstr.split("/");
            if (trmps.length > 0) {
                forum_id = trmps[0];
                if (trmps.length > 1) {
                    discussion_id = trmps[1];
                    loadDiscussion(discussion_id);
                }
                else {
                    loadForum(forum_id);
                }
            }
//                loadForum(forum_id);
//              initForumPanel(discussion_id);
        }
        else initForumEntry(cls_id);
    }
    
    public void initForumEntry(String cls_id_) {
        RootPanel.get().clear();
        VerticalPanel hpanel = new VerticalPanel();
//      hpanel.setSize("100%", "100%");
        hpanel.setWidth("100%");

        CaptionPanel load_forum = new CaptionPanel("Please choose an entry");
        hpanel.add(load_forum);
        hpanel.setCellHorizontalAlignment(load_forum, HorizontalPanel.ALIGN_CENTER);
        load_forum.add(forum_list_panel);
        load_forum.setWidth("300px");
        RootPanel.get().add(hpanel);
        
//      CaptionPanel new_post = new CaptionPanel("newly added dicussion topics");
//      hpanel.add(new_post);
//      hpanel.setCellHorizontalAlignment(new_post, HorizontalPanel.ALIGN_CENTER);
//      new_post.add(new_discussion_list_panel);
//      new_post.setWidth("300px");
        loadForumList(cls_id_);
//      RootPanel.get().add(hpanel);
//      feedForumList();
//      feedNewPostsList();
        
        HorizontalPanel forum_entry_editing_hpanel = new HorizontalPanel();
        hpanel.add(forum_entry_editing_hpanel);
        forum_entry_editing_hpanel.setWidth("300px");
        Label new_entry = new Label("New");
        forum_entry_editing_hpanel.add(new_entry);
        hpanel.setCellHorizontalAlignment(forum_entry_editing_hpanel, HorizontalPanel.ALIGN_CENTER);
        
        text_box_hpanel = new HorizontalPanel();
        hpanel.add(text_box_hpanel);
        text_box_hpanel.setWidth("300px");
        hpanel.setCellHorizontalAlignment(text_box_hpanel, HorizontalPanel.ALIGN_CENTER);
        
        
        TextBox text_box = new TextBox();
        text_box.setText("Input the name of the entry");
        
        text_box.setWidth("250px");
        
        text_box.addFocusHandler(new FocusHandler() {
            public void onFocus(FocusEvent event) {
                TextBox box = (TextBox)event.getSource();
                String tmp_str = box.getText();
                if (tmp_str.equalsIgnoreCase("Input the name of the entry")) {
                    box.setText("");
                }
                else {
                    return;
                }
            }
          });
          
        text_box.addBlurHandler(new BlurHandler() {
            public void onBlur(BlurEvent event) {
                TextBox box = (TextBox)event.getSource();
                String tmp_str = box.getText();
                if (tmp_str.equalsIgnoreCase("Input the name of the entry") || tmp_str.trim().equalsIgnoreCase("")) {
                    box.setText("Input the name of the entry");
                }
                else {
                    return;
                }
            }
          });
        
        text_box_hpanel.add(text_box);
        
        Button btn = new Button("Create");
        text_box_hpanel.add(btn);
        text_box_hpanel.setVisible(false);
        
        new_entry.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (text_box_hpanel.isVisible()) {
                    text_box_hpanel.setVisible(false);
                }
                else {
                    text_box_hpanel.setVisible(true);
                }
            }
        });
        
        btn.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                Button btn = (Button)event.getSource();
                HorizontalPanel hpanel = (HorizontalPanel) btn.getParent();
                TextBox box = (TextBox) hpanel.getWidget(0);
                
                String url = "http://cscl.ist.psu.edu:5678/classconversation/service/ForumService";
//                String postData = "op=ce&t=0&cls=" + cls_id + "&cnt=" + box.getValue();
                String postData = "op=ce&cnt=" + box.getText() + "&cls=" + cls_id + "&uid=" + user_id;
                RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
                builder.setHeader("Content-type", "application/x-www-form-urlencoded");
                try {
                  Request request = builder.sendRequest(postData, new RequestCallback() {
                    public void onError(Request request, Throwable exception) {
                      displayError("Couldn't retrieve JSON");
                    }

                    public void onResponseReceived(Request request, Response response) {
                          if (200 == response.getStatusCode()) {
                              initForumEntry(cls_id);
                          } else {
                            displayError("Error!");
                          }
                    }
                  });
                } catch (RequestException e) {
                  displayError("Couldn't retrieve JSON");
                }
            }
        });
    }
    
    public void loadForumList(String cls_id){
        String url = "http://cscl.ist.psu.edu:5678/classconversation/service/ForumService";
        String postData = "op=gforums&t=0&o=time asc&cls=" + cls_id;
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
        builder.setHeader("Content-type", "application/x-www-form-urlencoded");
        try {
          Request request = builder.sendRequest(postData, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              displayError("Couldn't retrieve JSON");
            }

            public void onResponseReceived(Request request, Response response) {
                  if (200 == response.getStatusCode()) {
                      forum_list_panel.clear();
                      forum_list_panel.setSize("100%", "100%");
                      JsArray<CommonObject> forums = asArrayOfCommonObject(response.getText());
                      for (int i = 0; i < forums.length(); i++) {
                          final CommonObject forum = forums.get(i);
                          Label forum_label = new Label(forums.get(i).getContent(), false);
                          forum_label.addStyleName("clickable-label");
                          forum_label.addClickHandler(new ClickHandler() {
                            public void onClick(ClickEvent event) {
                                String url = Window.Location.getHref();
                                if (url.indexOf('#') > -1) {
                                    String hash = Window.Location.getHash();
                                    Window.Location.replace(url + forum.getId());
//                                  initObjectViewerMenuBar();
                                    loadForum(forum.getId());
                                }
                                else {
                                    Window.Location.replace(url + "#" + forum.getId());
//                                    initObjectViewerMenuBar();
                                    loadForum(forum.getId());
                                }
//                              Window.Location.replace(GWT.getModuleBaseURL() + )
                            }
                        });
                          forum_list_panel.add(forum_label);
                      }
                  } else {
                    displayError("Error!");
                  }
            }
          });
        } catch (RequestException e) {
          displayError("Couldn't retrieve JSON");
        }
    }
    
    public void loadDiscussion(String id) {
        String url1 = Window.Location.getHref();
        if (url1.indexOf('#') > -1) {
            String hash = Window.Location.getHash();
            if (hash.indexOf('/') > -1) {
                String temp = replaceDiscussionID(hash, id);
                url1 = url1.substring(0, url1.indexOf('#'));
                Window.Location.replace(url1 + temp);
            }
            else {
                Window.Location.replace(url1 + "/" + id);
            }
        }
        else {
        }
        right_panel.clear();
        posts_vpanel.clear();
        
        String url = "http://cscl.ist.psu.edu:5678/classconversation/service/ForumService";
        String postData = "op=goc&t=2&o=time asc&fid=" + id;
        discussion_id = id;
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
        builder.setHeader("Content-type", "application/x-www-form-urlencoded");
        try {
          Request request = builder.sendRequest(postData, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              displayError("Couldn't retrieve JSON");
            }

            public void onResponseReceived(Request request, Response response) {
                  if (200 == response.getStatusCode()) {
                      JsArray<CommonObject> discussions = asArrayOfCommonObject(response.getText());
                      CommonObject obj;
                      CommonObject post;
                      for (int i = 0; i < discussions.length(); i++) {
                          obj = discussions.get(i);
                          anchor_description.clear();
                          anchor_description.add(new HTML(obj.getContent()));
                          JsArray<CommonObject> posts = obj.getItems();
                          if (posts != null && posts.length() > 0) {                        
                              for (int j = 0; j < posts.length(); j++) {
                                  post = posts.get(j);
                                  GWTCBox post_box = new GWTCBox(GWTCBox.STYLE_GREY);
                                  post_box.setWidth("100%");
                                  HorizontalPanel container = new HorizontalPanel();
                                  container.addStyleName("post-meta-info");
                                  container.setWidth("100%");
                                  Image post_icon = null;
                                  if (post.getItemType() == 0) {
                                      post_icon = new Image(box_paper_icon);
                                      post_icon.setTitle("Adding new info");
                                  }
                                  else if (post.getItemType() == 1) {
                                      post_icon = new Image(question_mark_icon);
                                      post_icon.setTitle("Questioning");
                                  }
                                  else if (post.getItemType() == 2) {
                                      post_icon = new Image(organization_icon);
                                      post_icon.setTitle("Organization & Structure");
                                  }
                                  else if (post.getItemType() == 3) {
                                      post_icon = new Image(thumb_up_down_icon);
                                      post_icon.setTitle("Agree/Disagree");
                                  }
                                  else if (post.getItemType() == 4) {
                                      post_icon = new Image(box_other_stuff_icon);
                                      post_icon.setTitle("Have something else to say");
                                  }
                                  post_icon.setSize("45px", "45px");
    
                                  VerticalPanel post_meta_info_vpanel = new VerticalPanel();
                                  post_meta_info_vpanel.setWidth("80px");
                                  post_meta_info_vpanel.addStyleName("post-meta-info");
                                  post_meta_info_vpanel.add(post_icon);
                                  post_meta_info_vpanel.setCellHorizontalAlignment(post_icon, HorizontalPanel.ALIGN_RIGHT);
    
                                  VerticalPanel post_user_info = new VerticalPanel();
                                  Label user_lable = new Label(fitString(post.getUserFullNameFromObject(), 15));
                                  user_lable.addStyleName("username");
                                  user_lable.getElement().setAttribute("user_id", post.getUser());
                                  user_lable.addClickHandler(new ClickHandler() {
                                      public void onClick(ClickEvent event) {
    //                                    Label user = (Label)event.getSource();
    //                                    getProfileX(user.getElement().getAttribute("user_id"), user);
                                      }
                                  });
                                  post_user_info.add(user_lable);
                                    
                                  Date date = new Date();
                                  date.setTime(Long.valueOf(post.getCreationTime()));
                                  Label creation_time = new Label(DateTimeFormat.getShortDateTimeFormat().format(date));
                                  creation_time.addStyleName("post-time");
                                  post_user_info.add(creation_time);
                                  post_user_info.addStyleName("post-user-info");
                                      
                                      
                                  post_meta_info_vpanel.add(post_user_info);
                                  VerticalPanel post_comment_vpanel = new VerticalPanel();
                                  post_comment_vpanel.setWidth("100%");
                                  SimplePanel post_content = new SimplePanel();
                                  HTML post_content_label = new HTML(post.getContent());
                                  post_content_label.setWidth("100%");
                                  post_content.add(post_content_label);
                                  post_comment_vpanel.add(post_content);
                                      
                                  Label comment_label = new Label("Show/Hide Comments (" + post.getLikes() + ")");
                                  comment_label.getElement().setAttribute("post_id", post.getId());
                                  comment_label.addStyleName("clickable-label");
                                  post_comment_vpanel.add(comment_label);
                                  post_comment_vpanel.setCellHorizontalAlignment(comment_label, HorizontalPanel.ALIGN_LEFT);
                                    
                                  comment_label.addClickHandler(new ClickHandler() {
                                      public void onClick(ClickEvent event) {
                                          Label comment_label = (Label)event.getSource();
                                          VerticalPanel vpanel = (VerticalPanel)comment_label.getParent();
                                          if (vpanel.getWidgetCount() > 2) {
                                              while (vpanel.getWidgetCount() > 2) {
                                                  vpanel.remove(2);
                                              }
                                              open_commentpanel_counter--;
                                              if (open_commentpanel_counter == 0) {
                                            	  repeatPostLoader.scheduleRepeating(30000);
                                              }
                                              return;
                                          }
                                          open_commentpanel_counter++;
                                          if (open_commentpanel_counter > 0) {
                                        	  repeatPostLoader.cancel();
                                          }
                                          loadCommentsView(comment_label.getElement().getAttribute("post_id"), (VerticalPanel)comment_label.getParent());
                                          
                                      }
                                  });
                                    
                                  container.add(post_meta_info_vpanel);
                                  container.add(post_comment_vpanel);
                                  post_box.add(container);
                                  posts_vpanel.add(post_box);
                            }
                    }
                 }
             } else {
                displayError("Error!");
             }
            }
          });
        } catch (RequestException e) {
          displayError("Couldn't retrieve JSON");
        }
        
        String url2 = "http://cscl.ist.psu.edu:5678/classconversation/service/ForumService?op=ga&operator=xx&fid=" + id;
        RequestBuilder builder1 = new RequestBuilder(RequestBuilder.GET, url2);
        builder1.setHeader("Content-type", "application/x-www-form-urlencoded");
        try {
            Request request2 = builder1.sendRequest(null, new RequestCallback() {
              public void onError(Request request, Throwable exception) {
                displayError("Couldn't retrieve JSON");
              }

              public void onResponseReceived(Request request, Response response) {
                    if (200 == response.getStatusCode()) {
                        if (response.getHeader("Content-Type").equalsIgnoreCase("text/plain") && response.getText().equalsIgnoreCase("No attachment found")) {
                            anchor_viewer.setSplitPosition("100%");
                        }
                        else {
                            anchor_viewer.setSplitPosition(anchor_viewer.getOffsetHeight() * 0.3 + "px");
                        }
                        
                        String url = "http://cscl.ist.psu.edu:5678/classconversation/service/ForumService";
                        String postData = "op=goc&t=2&o=time asc&fid=" + discussion_id;
                        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
                        builder.setHeader("Content-type", "application/x-www-form-urlencoded");
                        try {
                          Request request1 = builder.sendRequest(postData, new RequestCallback() {
                            public void onError(Request request, Throwable exception) {
                              displayError("Couldn't retrieve JSON");
                            }

                            public void onResponseReceived(Request request, Response response) {
                                  if (200 == response.getStatusCode()) {
                                          JsArray<CommonObject> discussions = asArrayOfCommonObject(response.getText());
                                          CommonObject obj;
                                          if (discussions.length() > 0) {
                                              obj = discussions.get(0);
                                              if (obj.getContent().length() == 0 || obj.getContent().equalsIgnoreCase("Enter content here.")) {
                                                  anchor_viewer.setSplitPosition("0%");
                                              }
                                          }
                                  } else {
                                    displayError("Error!");
                                  }
                            }
                          });
                        } catch (RequestException e) {
                          displayError("Couldn't retrieve JSON");
                        }
                            
                    } else {
                      displayError("Error!");
                    }
              }
            });
          } catch (RequestException e) {
            displayError("Couldn't retrieve JSON");
          }
        
        Frame frame = new Frame("http://cscl.ist.psu.edu:5678/classconversation/service/ForumService?op=ga&operator=xx&fid=" + id);
        frame.addStyleName("my-frame");
        frame.setSize("100%", "100%");
        
        Window.addResizeHandler(new ResizeHandler() {
            public void onResize(ResizeEvent event) {
            }
        });
        
        RootPanel.get().clear();
        right_panel.setSize("100%", "100%");
//      discussion_vpanel.setSize("100%", "100%");
        discussion_vpanel.setWidth("100%");
        right_panel.add(discussion_vpanel);
        hsplitpanel.setSize("100%", "100%");
        hsplitpanel.setLeftWidget(left_panel);
        left_panel.setWidth("100%");
        left_panel.setHeight("100%");
        hsplitpanel.setRightWidget(right_panel);
        RootPanel.get().add(hsplitpanel);
        
        hsplitpanel.setSplitPosition(0.7*hsplitpanel.getOffsetWidth() + "px");
        left_panel.add(menu_bar);
        left_panel.setCellHeight(menu_bar, "32px");
        
        anchor_file = new VerticalPanel();
        
        Image closing_icon_image = new Image(closing_icon);
        closing_icon_image.setSize("16", "16");
        closing_icon_image.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                anchor_viewer.setSplitPosition("100%");
            }
        });
        
        anchor_description.setSize("100%", "100%");
        anchor_description.add(new Label("loading..."));
        anchor_file.setSize("100%", "100%");
        
        HorizontalPanel closing_sp = new HorizontalPanel();
        closing_sp.setHeight("16px");
        closing_sp.setWidth("100%");
        closing_sp.add(closing_icon_image);
        closing_sp.setCellHorizontalAlignment(closing_icon_image, HorizontalPanel.ALIGN_RIGHT);
        
        anchor_file.add(closing_sp);
        
        anchor_file.setCellHeight(closing_sp, "16px");

        anchor_file.add(frame);
        anchor_file.setCellHorizontalAlignment(frame, HorizontalPanel.ALIGN_CENTER);
        
        anchor_viewer.setSize("100%", "100%");
        anchor_viewer.setTopWidget(anchor_description);
        anchor_viewer.setBottomWidget(anchor_file);
        left_panel.setSize("100%", "100%");
        left_panel.add(anchor_viewer);
        repeatPostLoader.scheduleRepeating(1000 * 60);
    }
    
    private void loadCommentsView(String post_id, VerticalPanel post_comment_vpanel) {
        final VerticalPanel post_comment_vpanel_ = post_comment_vpanel;
        final String post_id_ = post_id;
        if (post_comment_vpanel_.getWidgetCount() > 2) {
            while (post_comment_vpanel_.getWidgetCount() > 2) {
                post_comment_vpanel_.remove(2);
            }
//            return;
        }
//        final VerticalPanel post_comment_vpanel_ = post_comment_vpanel;
        final VerticalPanel comments_panel = new VerticalPanel();
        comments_panel.setWidth("100%");
        String url = "http://cscl.ist.psu.edu:5678/classconversation/service/ForumService";
        String postData = "op=goc&t=3&o=time asc&fid=" + post_id_;
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
        builder.setHeader("Content-type","application/x-www-form-urlencoded");
        try {
            Request request = builder.sendRequest(postData, new RequestCallback() {
                public void onError(Request request, Throwable exception) {
                    displayError("Couldn't retrieve JSON");
                  }
                  public void onResponseReceived(Request request, Response response) {
                      if (200 == response.getStatusCode()) {
//                          posts_vpanel.clear();
                          JsArray<CommonObject> posts = asArrayOfCommonObject(response.getText());
                          CommonObject post = posts.get(0);
                          JsArray<CommonObject> comments = post.getItems();
                          CommonObject comment;
                          Date date = new Date();
                          if (comments.length() > 0) {
                              for (int i = 0; i < comments.length(); i++) {
                                  comment = comments.get(i);
                                  date.setTime(Long.valueOf(comment.getCreationTime()));
                                  VerticalPanel seg_panel = new VerticalPanel();
                                  seg_panel.setWidth("100%");
                                  seg_panel.add(new HTML(comment.getContent()));
                                  seg_panel.add(new HTML("------" + fitString(comment.getUserFullNameFromObject(), 15) + " at " + DateTimeFormat.getShortDateTimeFormat().format(date)));
                                  seg_panel.setCellHorizontalAlignment(seg_panel.getWidget(1), HorizontalPanel.ALIGN_RIGHT);
                                  seg_panel.setStyleName("comment-item");
                                  comments_panel.add(seg_panel);
                              }
                              Label comment_label = (Label) post_comment_vpanel_.getWidget(1);
                              comment_label.setText("Show/Hide Comments (" + post.getLikes() + ")");
                          }
                      }
                      else {
                          displayError("Error");
                      }
                  }
            });
        } catch (RequestException e) {
          displayError("Couldn't retrieve JSON");
        }
        
        VerticalPanel new_comment_vpanel = new VerticalPanel();
        new_comment_vpanel.setWidth("100%");
        final TextArea comment_text_input = new TextArea();
        comment_text_input.setWidth("100%");
        comment_text_input.setHeight("70px");
        
        HTML submit_button = new HTML("<div>Submit<span/><div>");
        submit_button.setStyleName("round-button-8");
        submit_button.getElement().setId("round-button-g-8");
        
        submit_button.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                String msg = comment_text_input.getValue();
                if (msg.length() == 0) {
                    Window.alert("No empty message can be sent");
                    comment_text_input.setValue("");
                    comment_text_input.setText("");
                    comment_text_input.setCursorPos(0);
                    return;
                }
                String found = isInputInvalid("/(\\{1,})/gi", msg);
                if (found.equalsIgnoreCase("true")) {
                    Window.alert("Character \\ should be in even number in a sequence");
                    return;
                }
                
                String content = msg;
                content = content.replaceAll("[\\r\\n]", "<br>");
                content = replaceURLWithHTMLLinks(content);
                content = URL.encodeComponent(content);
                
                String url = URL.encode("http://cscl.ist.psu.edu:5678/classconversation/service/ForumService");
                String postData = "op=ac&&parentid=" + post_id_ + "&cnt=" + content + "&cls=" + cls_id + "&uid=" + user_id;
                RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
                builder.setHeader("Content-type", "application/x-www-form-urlencoded");
                try {
                  Request request = builder.sendRequest(postData, new RequestCallback() {
                    public void onError(Request request, Throwable exception) {
                      displayError("Couldn't retrieve JSON");
                    }

                    public void onResponseReceived(Request request, Response response) {    
                        if (200 == response.getStatusCode())    
                          {
                            comment_text_input.setValue("");
                            comment_text_input.setText("");
                            comment_text_input.setCursorPos(0);
                            comment_text_input.cancelKey();
                            String post_content = ((Label)((SimplePanel)post_comment_vpanel_.getWidget(0)).getWidget()).getText();
//                            loadCommentsView(post_id_, post_comment_vpanel_);
//                            loadPostView(open_item_id);

//                            String user_name = getUserFullname(loggin);
//                            if (ws_id.equalsIgnoreCase(ws_need_notification)) {
//	                            sendNotification(post_id_, "You have a new comment on the anchored discussion forum", user_name + " just commented on your post [\"" + post_content.substring(0, 50) + "\"]! <br><br>"
//	                                    + " <a href=\"http://cscl.ist.psu.edu:4567/Neptune/jsp/forum.html?ws_id=" + ws_id + "\">Login to read the message </a>!" + 
//	                                    "<br><br> This is an automatically generated message.");
//                            }
//                            else {
//                            	
//                            }
                          }
                          else 
                          {
                            displayError("Couldn't retrieve JSON (" + response.getStatusText()
                                + ")");
                          }
                    }
                  });
                } catch (RequestException e) {
                  displayError("Couldn't retrieve JSON");
                }   
            }
        });
        
        new_comment_vpanel.add(comment_text_input);
        new_comment_vpanel.add(submit_button);
        post_comment_vpanel.add(comments_panel);
        post_comment_vpanel.add(new_comment_vpanel);
    }
    
    private void loadEmptyDiscussion() {
        right_panel.clear();
        posts_vpanel.clear();
        
        
        Window.addResizeHandler(new ResizeHandler() {
            public void onResize(ResizeEvent event) {
            }
        });
        
        RootPanel.get().clear();
        right_panel.setSize("100%", "100%");
//      discussion_vpanel.setSize("100%", "100%");
        discussion_vpanel.setWidth("100%");
//        right_panel.add(discussion_vpanel);   
        hsplitpanel.setSize("100%", "100%");
        hsplitpanel.setLeftWidget(left_panel);
        left_panel.setWidth("100%");
        left_panel.setHeight("100%");
        hsplitpanel.setRightWidget(right_panel);
        RootPanel.get().add(hsplitpanel);
        
        hsplitpanel.setSplitPosition(0.7*hsplitpanel.getOffsetWidth() + "px");
        left_panel.add(menu_bar);
        left_panel.setCellHeight(menu_bar, "32px");
        
        anchor_file = new VerticalPanel();
        
        Image closing_icon_image = new Image(closing_icon);
        closing_icon_image.setSize("16", "16");
        closing_icon_image.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                anchor_viewer.setSplitPosition("100%");
            }
        });
        
        anchor_description.setSize("100%", "100%");
        anchor_description.add(new HTML("Click  the third icon above to create new disussion in this forum!"));
        anchor_file.setSize("100%", "100%");
        
        HorizontalPanel closing_sp = new HorizontalPanel();
        closing_sp.setHeight("16px");
        closing_sp.setWidth("100%");
        closing_sp.add(closing_icon_image);
        closing_sp.setCellHorizontalAlignment(closing_icon_image, HorizontalPanel.ALIGN_RIGHT);
        
        anchor_file.add(closing_sp);
        
        anchor_file.setCellHeight(closing_sp, "16px");

        
        anchor_viewer.setSize("100%", "100%");
        anchor_viewer.setTopWidget(anchor_description);
        anchor_viewer.setBottomWidget(anchor_file);
        left_panel.setSize("100%", "100%");
        left_panel.add(anchor_viewer);
        anchor_viewer.setSplitPosition(anchor_viewer.getOffsetHeight() * 0.3 + "px");
    }
    
    private void loadPosts(String id) {
        String url = "http://cscl.ist.psu.edu:5678/classconversation/service/ForumService";
        String postData = "op=goc&t=2&o=time asc&fid=" + id;
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
        builder.setHeader("Content-type", "application/x-www-form-urlencoded");
        try {
          Request request = builder.sendRequest(postData, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              displayError("Couldn't retrieve JSON");
            }

            public void onResponseReceived(Request request, Response response) {
                  if (200 == response.getStatusCode()) {
//                    int post_number = new_post_vpanel.getWidgetCount() - 2;
//                    for (int i = 0; i < post_number; i++) {
//                        new_post_vpanel.remove(0);
//                    }
                      posts_vpanel.clear();
                      JsArray<CommonObject> discussions = asArrayOfCommonObject(response.getText());
                      CommonObject obj;
                      CommonObject post;
                      for (int i = 0; i < discussions.length(); i++) {
                          obj = discussions.get(i);
                          JsArray<CommonObject> posts = obj.getItems();
                          for (int j = posts.length(); j > 0; j--) {
                              post = posts.get(j - 1);
                                GWTCBox post_box = new GWTCBox(GWTCBox.STYLE_GREY);
                                post_box.setWidth("100%");
                                HorizontalPanel container = new HorizontalPanel();
                                container.addStyleName("post-meta-info");
                                container.setWidth("100%");
                                Image post_icon = null;
                                if (post.getItemType() == 0) {
                                    post_icon = new Image(box_paper_icon);
                                    post_icon.setTitle("Adding new info");
                                }
                                else if (post.getItemType() == 1) {
                                    post_icon = new Image(question_mark_icon);
                                    post_icon.setTitle("Questioning");
                                }
                                else if (post.getItemType() == 2) {
                                    post_icon = new Image(organization_icon);
                                    post_icon.setTitle("Organization & Structure");
                                }
                                else if (post.getItemType() == 3) {
                                    post_icon = new Image(thumb_up_down_icon);
                                    post_icon.setTitle("Agree/Disagree");
                                }
                                else if (post.getItemType() == 4) {
                                    post_icon = new Image(box_other_stuff_icon);
                                    post_icon.setTitle("Have something else to say");
                                }
                                post_icon.setSize("45px", "45px");

                                VerticalPanel post_meta_info_vpanel = new VerticalPanel();
                                post_meta_info_vpanel.setWidth("80px");
                                post_meta_info_vpanel.addStyleName("post-meta-info");
                                post_meta_info_vpanel.add(post_icon);
                                post_meta_info_vpanel.setCellHorizontalAlignment(post_icon, HorizontalPanel.ALIGN_RIGHT);

                                VerticalPanel post_user_info = new VerticalPanel();
                                Label user_lable = new Label(fitString(post.getUserFullNameFromObject(), 15));
                                user_lable.addStyleName("username");
                                user_lable.getElement().setAttribute("user_id", post.getUser());
                                post_user_info.add(user_lable);
                                  
                                Date date = new Date();
                                date.setTime(Long.valueOf(post.getCreationTime()));
                                Label creation_time = new Label(DateTimeFormat.getShortDateTimeFormat().format(date));
                                creation_time.addStyleName("post-time");
                                post_user_info.add(creation_time);
                                post_user_info.addStyleName("post-user-info");
                                    
                                post_meta_info_vpanel.add(post_user_info);
                                VerticalPanel post_comment_vpanel = new VerticalPanel();
                                post_comment_vpanel.setWidth("100%");
                                SimplePanel post_content = new SimplePanel();
                                HTML post_content_label = new HTML(post.getContent());
                                post_content_label.setWidth("100%");
                                post_content.add(post_content_label);
                                post_comment_vpanel.add(post_content);
                                    
                                Label comment_label = new Label("Show/Hide Comments (" + post.getLikes() + ")");
                                comment_label.getElement().setAttribute("post_id", post.getId());
                                comment_label.addStyleName("clickable-label");
                                post_comment_vpanel.add(comment_label);
                                post_comment_vpanel.setCellHorizontalAlignment(comment_label, HorizontalPanel.ALIGN_LEFT);
                                  
                                comment_label.addClickHandler(new ClickHandler() {
                                    public void onClick(ClickEvent event) {

                                        Label comment_label = (Label)event.getSource();
                                        VerticalPanel vpanel = (VerticalPanel)comment_label.getParent();
                                        if (vpanel.getWidgetCount() > 2) {
                                            while (vpanel.getWidgetCount() > 2) {
                                                vpanel.remove(2);
                                            }
                                            open_commentpanel_counter--;
                                            if (open_commentpanel_counter == 0) {
                                            	repeatPostLoader.scheduleRepeating(30000);
                                            }
                                            return;
                                        }
                                        open_commentpanel_counter++;
                                        if (open_commentpanel_counter > 0) {
                                        	repeatPostLoader.cancel();
                                        }
                                        loadCommentsView(comment_label.getElement().getAttribute("post_id"), (VerticalPanel)comment_label.getParent());
                                    }
                                });
                                  
                                container.add(post_meta_info_vpanel);
                                container.add(post_comment_vpanel);
                                post_box.add(container);
                                posts_vpanel.insert(post_box, 0);
                          }
                      }
//                      discussion_vpanel.add(new_post_vpanel);
                  } else {
                    displayError("Error!");
                  }
            }
          });
        } catch (RequestException e) {
          displayError("Couldn't retrieve JSON");
        }
    }
    
    
    private  void addBehaviour(Element splitter) {

        Event.setEventListener(splitter, new EventListener() {
            public void onBrowserEvent(Event event) {
                Window.alert(event.getType());
                if(event.getTypeInt() == Event.ONCLICK) {
                    hsplitpanel.setSplitPosition("100%");
                }
            }
        });
        Event.sinkEvents(splitter, Event.ONCLICK);
 }
    
    private int calculateCloseIconY() {
        return 0;
    }

    private int calculateCloseIconX() {
        return anchor_file.getOffsetWidth() - 16;
    }
    
    public String fitString(String original, int length) {
        int original_length = original.length();
        if (original_length > length) {
            return original.substring(0, length - 3) + "...";
        }
        else return original;
    }

    public void feedForumList() {
        forum_list_panel.clear();
        forum_list_panel.setSize("100%", "100%");
        String[] forum_names = {
                "hello",
                "Lord of the rings",
                "The dark Knight",
                "Batman returns",
                "Topics from ClassCommons"
        };
        for (int i = 0; i < forum_names.length; i++) {
            forum_list_panel.add(new Label(forum_names[i]));
        }
    }
    
    public void feedNewPostsList() {
        new_discussion_list_panel.clear();
        new_discussion_list_panel.setSize("100%", "100%");
        String[] forum_names = {
                "hello",
                "Lord of the rings",
                "The dark Knight",
                "Batman returns",
                "Topics from ClassCommons"
        };
        for (int i = 0; i < forum_names.length; i++) {
            new_discussion_list_panel.add(new Label(forum_names[i]));
        }
    }
    
    public void feedDocs(String id, String order) {
//      forum_id = id;
        String url = URL.encode("http://cscl.ist.psu.edu:5678/classconversation/service/ForumService");
        String postData = "op=goc&t=1&fid=" + id + "&o=" + order;
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
        builder.setHeader("Content-type", "application/x-www-form-urlencoded");
        try {
          Request request = builder.sendRequest(postData, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              displayError("Couldn't retrieve JSON");
            }

            public void onResponseReceived(Request request, Response response) {    
                if (200 == response.getStatusCode())    
                  {
                    JsArray<CommonObject> forums = asArrayOfCommonObject(response.getText());
                    CommonObject forum;
                    CommonObject discussion;
                    JsArray<CommonObject> discussions;
                    if (forums.length() > 0) {
//                        file_list_hpanel.clear();
                        forum = forums.get(0);
                        discussions = forum.getItems();
                        for (int i = 0; i < discussions.length(); i++) {
                            discussion = discussions.get(i);
                            Image photo = new Image(topic_icon);
                            VerticalPanel icon_vpanel = new VerticalPanel();
                            icon_vpanel.add(photo);
//                            icon_vpanel.add(new Label(discussion.getContent()));
                            icon_vpanel.add(new Label(discussion.getTitle()));
                            photo.getElement().setAttribute("item-id", discussion.getId());
//                          icon_vpanel.addStyleName("highlighted-doc-icon");
                            photo.addMouseOverHandler(new MouseOverHandler() {
                                public void onMouseOver(MouseOverEvent event) {
                                    if (highlighted_doc_icon != null) {
                                        highlighted_doc_icon.removeStyleName("highlighted-doc-icon");
                                    }
                                    Image photo = (Image)event.getSource();
                                    VerticalPanel icon_vpanel = (VerticalPanel)photo.getParent();
                                    icon_vpanel.addStyleName("highlighted-doc-icon");
                                    highlighted_doc_icon = icon_vpanel;
                                }
                            });
                            
                            photo.addMouseOutHandler(new MouseOutHandler() {
                                public void onMouseOut(MouseOutEvent event) {
                                    Image photo = (Image)event.getSource();
                                    VerticalPanel icon_vpanel = (VerticalPanel)photo.getParent();
                                    icon_vpanel.removeStyleName("highlighted-doc-icon");
                                    highlighted_doc_icon = null;
                                }
                            });
                            final int i_ = i;
                            photo.setPixelSize(32, 32);
                            photo.addStyleName("file-list-item");
                            
                            photo.addClickHandler(new ClickHandler() {
                                public void onClick(ClickEvent event) {
                                    Image photo = (Image)event.getSource();
                                    loadDiscussion(photo.getElement().getAttribute("item-id"));
                                }
                            });
                            
                            int row = i_/column_;
                            int column = i_%column_;
                            file_list_hpanel.setWidget(row, column, icon_vpanel);
                        }
                    }
                  }
                  else 
                  {
                    displayError("Couldn't retrieve JSON (" + response.getStatusText()
                        + ")");
                  }
            }
          });
        } catch (RequestException e) {
          displayError("Couldn't retrieve JSON");
        }   
    }
    
    public void feedDocIcons() {
        highlighted_doc_icon = null;
        Image icon_image = new Image(topic_icon);
//      ArrayList<Image> photos;
        for (int i = 0; i < 50; i++) {
            Image photo = new Image(topic_icon);
            VerticalPanel icon_vpanel = new VerticalPanel();
            icon_vpanel.add(photo);
            icon_vpanel.add(new Label("Lord of the rings"));
//          icon_vpanel.addStyleName("highlighted-doc-icon");
            photo.addMouseOverHandler(new MouseOverHandler() {
                public void onMouseOver(MouseOverEvent event) {
                    if (highlighted_doc_icon != null) {
                        highlighted_doc_icon.removeStyleName("highlighted-doc-icon");
                    }
                    Image photo = (Image)event.getSource();
                    VerticalPanel icon_vpanel = (VerticalPanel)photo.getParent();
                    icon_vpanel.addStyleName("highlighted-doc-icon");
                    highlighted_doc_icon = icon_vpanel;
                }
            });
            
            photo.addMouseOutHandler(new MouseOutHandler() {
                public void onMouseOut(MouseOutEvent event) {
                    Image photo = (Image)event.getSource();
                    VerticalPanel icon_vpanel = (VerticalPanel)photo.getParent();
                    icon_vpanel.removeStyleName("highlighted-doc-icon");
                    highlighted_doc_icon = null;
                }
            });
            final int i_ = i;
            photo.setPixelSize(32, 32);
            photo.addStyleName("file-list-item");
            int row = i_/column_;
            int column = i_%column_;
            file_list_hpanel.setWidget(row, column, icon_vpanel);
        }
    }
    
    private void initObjectViewerMenuBar() {
        menu_bar.addStyleName("df-menubar");
        menu_bar.add(object_viewer_menu_panel);
//        object_viewer_menu_panel.addStyleName("df-menubar");
        object_viewer_menu_panel.setHorizontalAlignment(HorizontalPanel.ALIGN_LEFT);
        
        
        Image class_selection_icon_image = new Image(class_selection_icon);
        class_selection_icon_image.setTitle("Class selection page");
        class_selection_icon_image.addStyleName("df-menuitem");
        class_selection_icon_image.setPixelSize(icon_width, icon_height);
        object_viewer_menu_panel.add(class_selection_icon_image);
        initClassSelectionIcon(class_selection_icon_image);
        
        Image home_icon_image = new Image(home_icon);
        home_icon_image.setTitle("Go to home of class");
        home_icon_image.addStyleName("df-menuitem");
        home_icon_image.setPixelSize(icon_width, icon_height);
        object_viewer_menu_panel.add(home_icon_image);
        initHomeIcon(home_icon_image);
        
        
        
        Image text_doc_icon_image = new Image(text_doc_icon);
        text_doc_icon_image.setTitle("Create a new document");
        text_doc_icon_image.addStyleName("df-menuitem");
        text_doc_icon_image.setPixelSize(icon_width, icon_height);
        object_viewer_menu_panel.add(text_doc_icon_image);
//        initNewDocIcon(text_doc_icon_image);
        initUploadIcon(text_doc_icon_image);

        Image edit_doc_icon_image = new Image(editor_icon);
        edit_doc_icon_image.setTitle("Create a new document");
        edit_doc_icon_image.addStyleName("df-menuitem");
        edit_doc_icon_image.setPixelSize(icon_width, icon_height);
        object_viewer_menu_panel.add(edit_doc_icon_image);
//        initNewDocIcon(text_doc_icon_image);
//        initUploadIcon(edit_doc_icon_image);
        
        
//        Image upload_doc_icon_image = new Image(upload_doc_icon);
//        upload_doc_icon_image.setTitle("Upload files");
//        upload_doc_icon_image.addStyleName("df-menuitem");
//        upload_doc_icon_image.setPixelSize(icon_width, icon_height);
//        object_viewer_menu_panel.add(upload_doc_icon_image);
//        initUploadIcon(upload_doc_icon_image);
        
        Image folder_icon_image = new Image(folder_icon);
        folder_icon_image.setTitle("Existing files");
        folder_icon_image.addStyleName("df-menuitem");
        folder_icon_image.setPixelSize(icon_width, icon_height);
        object_viewer_menu_panel.add(folder_icon_image);
        initListFile(folder_icon_image);
        
        Image recycle_icon_image = new Image(recycle_icon);
        recycle_icon_image.setTitle("Delete files");
        recycle_icon_image.addStyleName("df-menuitem");
        recycle_icon_image.setPixelSize(icon_width, icon_height);
        object_viewer_menu_panel.add(recycle_icon_image);
//        initRecycleIcon(recycle_icon_image);
        
        Image toggle_vert_image = new Image(toggle_vert);
        toggle_vert_image.setTitle("Toggle post panel");
        toggle_vert_image.addStyleName("df-menuitem");
        toggle_vert_image.setPixelSize(icon_width, icon_height);
        object_viewer_menu_panel.add(toggle_vert_image);
        initToggleAnchorIcon(toggle_vert_image);
        
        Image toggle_discussion_icon_image = new Image(toogle_dicussion_icon);
        toggle_discussion_icon_image.setTitle("Toggle post panel");
        toggle_discussion_icon_image.addStyleName("df-menuitem");
        toggle_discussion_icon_image.setPixelSize(icon_width, icon_height);
        object_viewer_menu_panel.add(toggle_discussion_icon_image);
        initToogleDiscussionIcon(toggle_discussion_icon_image);
        
        Image switch_icon_image = new Image(switch_icon);
        switch_icon_image.setTitle("Toggle post panel");
        switch_icon_image.addStyleName("df-menuitem");
        switch_icon_image.setPixelSize(icon_width, icon_height);
//        object_viewer_menu_panel.add(switch_icon_image);
//        initSwitchForumIcon(switch_icon_image);
        
        
//        Image config_icon_image = new Image(configuration_forum_icon);
//        config_icon_image.setTitle("Switch forum and see contacts");
//        config_icon_image.addStyleName("df-menuitem");
//        config_icon_image.setPixelSize(icon_width, icon_height);
//        object_viewer_menu_panel.add(config_icon_image);
//        initConfigurationIcon(config_icon_image);


        Image file_help_icon_image = new Image(file_help_icon);
        file_help_icon_image.setTitle("Help");
        file_help_icon_image.addStyleName("df-menuitem");
        file_help_icon_image.setPixelSize(icon_width, icon_height);
//        object_viewer_menu_panel.add(file_help_icon_image);
//        initHelpIcon(file_help_icon_image);
        
        Image class_commons_icon_image = new Image(class_commons_icon);
        class_commons_icon_image.setTitle("Go to class commons");
        class_commons_icon_image.addStyleName("df-menuitem");
        class_commons_icon_image.setPixelSize(icon_width, icon_height);
        object_viewer_menu_panel.add(class_commons_icon_image);
        initGoToCCommon(class_commons_icon_image);
        
        Image logout_icon_image = new Image(logout_icon);
        logout_icon_image.setTitle("Logout");
        logout_icon_image.addStyleName("df-menuitem");
        logout_icon_image.setPixelSize(icon_width, icon_height);
        object_viewer_menu_panel.add(logout_icon_image);
        initLogoutIcon(logout_icon_image);

        HorizontalPanel user_at_forum_hpanel = new HorizontalPanel();
        
        Label loggin_label = new Label(user.getFullName() + " @ ");
        loggin_label.setTitle("Current user");
        loggin_label.addStyleName("df-menuitem");
        loggin_label.addStyleName("df-menuitem-label");
        loggin_label.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                Label login_ = (Label)event.getSource();
            }
        });
        object_viewer_menu_panel.add(loggin_label);
        
        forum_name = new Label();
        forum_name.setTitle("Current forum");
        forum_name.addStyleName("df-menuitem");
        forum_name.addStyleName("df-menuitem-label");
        forum_name.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                Window.Location.reload();
            }
        });
        
        user_at_forum_hpanel.add(loggin_label);
        user_at_forum_hpanel.add(forum_name);
        menu_bar.add(user_at_forum_hpanel);
        menu_bar.setCellHorizontalAlignment(user_at_forum_hpanel, HorizontalPanel.ALIGN_RIGHT);
    }
    
    private void initClassSelectionIcon(Image class_selection_icon_image) {
        class_selection_icon_image.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                Window.alert("Redirect to class selection home!");
            }
        });
    }
    
    private void initHomeIcon(Image home_icon_image) {
        home_icon_image.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                Window.Location.replace(cls_home_url);
            }
        });
    }
    
//    private String getUserFullname(){
//        return user.getFullName();
//    }
    
    private void initUploadIcon(Image upload_doc_icon_image) {
        upload_doc_icon_image.addClickHandler(new ClickHandler() {
              public void onClick(ClickEvent event) {
                  final GWTCPopupBox upload_box = new GWTCPopupBox(GWTCPopupBox.OPTION_ROUNDED_BLUE);
                  
                  final FormPanel uploader_form_panel = new FormPanel();
                  uploader_form_panel.setAction("http://cscl.ist.psu.edu:5678/classconversation/service/ForumService"); //need to change to the actual url that handles uploading
                  uploader_form_panel.setEncoding(FormPanel.ENCODING_MULTIPART);
                  uploader_form_panel.setMethod(FormPanel.METHOD_POST);
                  
                  CaptionPanel upload_caption_panel = new CaptionPanel("Create a dicussion topic");
                  
                  final VerticalPanel upload_form_element_panel = new VerticalPanel();
                  upload_caption_panel.add(upload_form_element_panel);
                  uploader_form_panel.setWidget(upload_caption_panel);
                  
                  HorizontalPanel hpanel_1 = new HorizontalPanel();
                  Label title_label = new Label("Title: ");
                  hpanel_1.add(title_label);
                  final TextBox title = new TextBox();
                  title.setText("Untitled");
                  title.setName("title");
                  
                  title.addFocusHandler(new FocusHandler() {
                    public void onFocus(FocusEvent event) {
                        TextBox box = (TextBox)event.getSource();
                        String tmp_str = box.getText();
                        if (tmp_str.equalsIgnoreCase("Untitled")) {
                            box.setText("");
                        }
                        else {
                            return;
                        }
                    }
                  });
                  
                  title.addBlurHandler(new BlurHandler() {
                    public void onBlur(BlurEvent event) {
                        TextBox box = (TextBox)event.getSource();
                        String tmp_str = box.getText();
                        if (tmp_str.equalsIgnoreCase("Untitled") || tmp_str.trim().equalsIgnoreCase("")) {
                            box.setText("Untitled");
                        }
                        else {
                            return;
                        }
                    }
                  });
                  
                  hpanel_1.add(title);
                  upload_form_element_panel.add(hpanel_1);
                  
                  HorizontalPanel hpanel_2 = new HorizontalPanel();
                  Label content_label = new Label("Content: ");
//                  hpanel_2.add(content_label);
                  TextArea content_box = new TextArea();
                  content_box.setSize("300px", "100px");
                  content_box.setName("content");
                  content_box.setText("Enter content here.");
                  content_box.setVisible(false);
                  hpanel_2.add(content_box);
                  upload_form_element_panel.add(hpanel_2);
                  
                  content_box.addFocusHandler(new FocusHandler() {
                    public void onFocus(FocusEvent event) {
                        TextArea box = (TextArea)event.getSource();
                        String tmp_str = box.getText();
                        if (tmp_str.equalsIgnoreCase("Enter content here.")) {
                            box.setText("");
                        }
                        else {
                            return;
                        }
                    }
                  });
                    
                  content_box.addBlurHandler(new BlurHandler() {
                    public void onBlur(BlurEvent event) {
                        TextArea box = (TextArea)event.getSource();
                            String tmp_str = box.getText();
                            if (tmp_str.equalsIgnoreCase("Enter content here.") || tmp_str.trim().equalsIgnoreCase("")) {
                                box.setText("Enter content here.");
                            }
                            else {
                                return;
                            }
                    }
                  });
                  
                  
                  Hidden operator = new Hidden();
                  operator.setName("op");
                  operator.setValue("addAttachment");
                  upload_form_element_panel.add(operator);
    
                  Hidden redirector = new Hidden();
                  redirector.setName("redirect");
                  redirector.setValue("null");
                  upload_form_element_panel.add(redirector);
                  
                  Hidden hidden_itype_name = new Hidden();
                  hidden_itype_name.setName("itype");
                  hidden_itype_name.setValue("0");
                  upload_form_element_panel.add(hidden_itype_name);
                  
                  Hidden hidden_user_name = new Hidden();
                  hidden_user_name.setName("uid");
                  hidden_user_name.setValue(user_id);
                  upload_form_element_panel.add(hidden_user_name);
                  
                  Hidden hidden_class_id = new Hidden();
                  hidden_class_id.setName("cls");
                  hidden_class_id.setValue(cls_id);
                  upload_form_element_panel.add(hidden_class_id);
    
                  Hidden hidden_parent_id = new Hidden();
                  hidden_parent_id.setName("parent_id");
                  hidden_parent_id.setValue(forum_id);
                  upload_form_element_panel.add(hidden_parent_id);
    
                  Hidden hidden_object_type = new Hidden();
                  hidden_object_type.setName("type");
                  hidden_object_type.setValue("1");
                  upload_form_element_panel.add(hidden_object_type);
                  
                  
                  final FileUpload upload = new FileUpload() {
                      {
                          addDomHandler(new ChangeHandler() {
    
                              public void onChange(
                                      ChangeEvent event) {
                                  FileUpload upload = (FileUpload)event.getSource();
                                  VerticalPanel upload_form_element_panel = (VerticalPanel) upload.getParent();
                                  int upload_idx = upload_form_element_panel.getWidgetIndex(upload);
                                  VerticalPanel file_list = (VerticalPanel) upload_form_element_panel.getWidget(upload_idx - 1);
                                  file_list.clear();
                                  String[] names = getFiles(((FileUpload)event.getSource()).getElement());
                                  for (int i = 0; i < names.length; i++) {
                                      file_list.add(new Label(names[i]));
                                  }
                                  title.setText(names[0].substring(0, names[0].lastIndexOf('.')));
                              }
                          }, ChangeEvent.getType());
                      }
                  };
                  upload.setName("fname");
//                  upload.getElement().setAttribute("multiple", "");
                  upload_form_element_panel.add(new VerticalPanel());
                  upload_form_element_panel.add(upload);
                  
                  
               // Add a 'submit' button.
                  HTML submit_button = new HTML("<div>Submit<span/><div>");
                  submit_button.setStyleName("round-button");
                  submit_button.getElement().setId("round-button-g");
                  submit_button.addClickHandler(new ClickHandler() {
                    public void onClick(ClickEvent event) {
                        String[] names = getFiles(upload.getElement());
//                        if (names.length < 1) {
//                            Window.alert("No file is selected!");
//                            return;
//                        }
                        for (int i = 0; i < names.length; i++) {
                            if (!names[i].substring(names[i].lastIndexOf('.') + 1).equalsIgnoreCase("pdf")) {
//                                Window.alert("can't upload files not in pdf format");
//                                return;
                            }
                        }
                        uploader_form_panel.submit();
                    }
                  });
                  
                  HTML cancel_button = new HTML("<div>Cancel<span/><div>");
                  cancel_button.setStyleName("round-button");
                  cancel_button.getElement().setId("round-button-g");
                  cancel_button.addClickHandler(new ClickHandler() {
                    public void onClick(ClickEvent event) {
                        upload_box.hide();
                    }
                  });
                  
                  HorizontalPanel submit_cancel_button_panel = new HorizontalPanel();
                  submit_cancel_button_panel.add(submit_button);
                  submit_cancel_button_panel.add(cancel_button);
                  upload_form_element_panel.add(submit_cancel_button_panel);
    
                  // Add an event handler to the form.
                  uploader_form_panel.addSubmitHandler(new FormPanel.SubmitHandler() {
                    public void onSubmit(SubmitEvent event) {
                        String[] names = getFiles(upload.getElement());
//                        if (names.length < 1) {
//                            Window.alert("No file is selected!");
//                        }
                    }
                  });
                  uploader_form_panel.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
                    public void onSubmitComplete(SubmitCompleteEvent event) {
                        upload_box.hide();
                        loadDiscussion(getReturnID(event.getResults()));
                    }
                  });
                  

                  upload_box.add(uploader_form_panel);

                  int X_ = calculateXposition(event.getNativeEvent().getClientX(), Window.getClientWidth(), 200);
                  int Y_ = calculateYposition(event.getNativeEvent().getClientY(), Window.getClientHeight(), 100);
                  if (event.getNativeEvent().getClientY() + 200 > Window.getClientHeight()) {
                      upload_box.setPopupPosition(X_, Y_);
                  }
                  else {
                      upload_box.setPopupPosition(X_, Y_);
                  }
                  upload_box.setZIndex(9999);
                  upload_box.show();
              }
        });
    }

    public void initListFile(Image icon) {
        icon.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (right_panel.getWidgetCount() == 1) {
                    right_panel.clear();
                    right_panel.add(file_sorting_list_box);
                    right_panel.add(file_list_hpanel);
                    file_list_hpanel.clear();
                    right_panel.setCellWidth(file_list_hpanel, "95%");
                    right_panel.setCellHeight(file_list_hpanel, "95%");
                    file_list_hpanel.setWidth("100%");
                    file_list_hpanel.setHeight("100%");
                    feedDocs(forum_id, "time desc");
                }
                else {
                    if (right_panel.getWidget(1) instanceof VerticalPanel) {
                        discussion_vpanel.removeFromParent();
                        right_panel.add(file_sorting_list_box);
                        right_panel.add(file_list_hpanel);
                        file_list_hpanel.clear();
//                        filelist.clear();
                        right_panel.setCellWidth(file_list_hpanel, "95%");
                        right_panel.setCellHeight(file_list_hpanel, "95%");
                        file_list_hpanel.setWidth("100%");
                        file_list_hpanel.setHeight("100%");
                        feedDocs(forum_id, "time desc");
                    }
                    else {
                        if (right_panel.getWidget(1) instanceof Grid) {
                            if (comment_loaded) {
                                right_panel.clear();
//                                right_panel.getWidget(0).removeFromParent();
                                right_panel.add(discussion_vpanel);
                            }
                            else {
                                right_panel.getWidget(0).removeFromParent();
                            }
                        }
                    }
                }
            }
        });
    }
    
    
    private void initNewPostPanel(){
        discussion_vpanel.clear();
        discussion_vpanel.add(posts_vpanel);
        discussion_vpanel.add(new_post_vpanel);
        posts_vpanel.setWidth("100%");
        new_post_vpanel.setWidth("100%");
        final TextArea post_text_input = new TextArea();
        post_text_input.setWidth("100%");
        post_text_input.setHeight("70px");
        final ListBox role_list = new ListBox(false);
        role_list.addItem("Select...", "unselected");
        role_list.addItem("Add info", "0");
        role_list.addItem("Question", "1");
        role_list.addItem("Organization", "2");
        role_list.addItem("Agree/Disagree", "3");
        role_list.addItem("Other", "4");
        HTML submit_button = new HTML("<div>Add to this topic<span/><div>");
        submit_button.setStyleName("round-button-8");
        submit_button.getElement().setId("round-button-g-8");
        HorizontalPanel role_box_submit_btn_panel = new HorizontalPanel();
        role_box_submit_btn_panel.setWidth("100%");
        role_box_submit_btn_panel.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
        
        
        HorizontalPanel role_submit_btn_hpanel = new HorizontalPanel();
//        role_box_submit_btn_panel.add(post_visual_cue_to_the_document);
        role_submit_btn_hpanel.add(role_list);
        role_submit_btn_hpanel.add(submit_button);
        
//        role_box_submit_btn_panel.add(role_list);
        role_box_submit_btn_panel.add(role_submit_btn_hpanel);
//        role_box_submit_btn_panel.setCellHorizontalAlignment(role_list, HorizontalPanel.ALIGN_RIGHT);
        role_box_submit_btn_panel.setCellHorizontalAlignment(role_submit_btn_hpanel, HorizontalPanel.ALIGN_RIGHT);
        new_post_vpanel.add(post_text_input);
        new_post_vpanel.add(role_box_submit_btn_panel);
        
        submit_button.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (discussion_id == null || discussion_id.length() < 1) {
                    Window.alert("There is no document or file open. To submit a post, you have to have an open document/file. Please click on the forth icon on the menubar to open a document/file!");
                    return;
                }
                String msg = post_text_input.getValue();
                String role = role_list.getValue(role_list.getSelectedIndex());
                if (msg.length() == 0) {
                    Window.alert("No empty message can be sent");
                    post_text_input.setValue("");
                    post_text_input.setText("");
                    post_text_input.setCursorPos(0);
                    return;
                }
//                if (msg.length() > 500) {
//                    Window.alert("The message is too long. The upper limit is 500 characters for a post!");
//                    return;
//                }
                String found = isInputInvalid("/(\\{1,})/gi", msg);
                if (found.equalsIgnoreCase("true")) {
                    Window.alert("Character \\ should be in even number in a sequence");
                    return;
                }
                if (role.equalsIgnoreCase("unselected")) {
                    Window.alert("Please select your stance on this topic from the dropdown list!");
                    return;
                }
                String parent_id;
//                if (open_item_id !=null && open_item_id != "") {
//                    parent_id = open_item_id;
//                }
//                else 
                parent_id = discussion_id;
                
                String content = post_text_input.getValue();
                content = content.replaceAll("[\\r\\n]", "<br>");
                content = replaceURLWithHTMLLinks(content);
                content = URL.encodeComponent(content);
                
//                Window.alert(content);
                String url = URL.encode("http://cscl.ist.psu.edu:5678/classconversation/service/ForumService");
                String postData = "op=ap&itype=" + role_list.getValue(role_list.getSelectedIndex()) + "&parentid=" + parent_id + 
                                    "&cnt=" + content + "&cls=" + cls_id + "&uid=" + user_id;
                RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
                builder.setHeader("Content-type", "application/x-www-form-urlencoded");
                try {
                  Request request = builder.sendRequest(postData, new RequestCallback() {
                    public void onError(Request request, Throwable exception) {
                      displayError("Couldn't retrieve JSON");
                    }

                    public void onResponseReceived(Request request, Response response) {    
                        if (200 == response.getStatusCode())    
                          {
                            post_text_input.setValue("");
                            post_text_input.setText("");
                            post_text_input.setCursorPos(0);
                            post_text_input.cancelKey();
                            loadPosts(discussion_id);
//                            String user_name = getUserFullname(loggin);
//                            if (ws_id.equalsIgnoreCase(ws_need_notification)) {
//                              sendNotification(open_item_id, "You have a new post on the anchored discussion forum", user_name + " added a post to the document [" + open_item_name + "] you uploaded! <br><br>"
//                                      + " <a href=\"http://cscl.ist.psu.edu:4567/Neptune/jsp/forum.html?ws_id=" + ws_id + "\">Login to read the message </a>" 
//                                      + "<br><br> This is an automatically generated message.");
//                            }
//                            else {
//                              
//                            }
                          }
                          else 
                          {
                            displayError("Couldn't retrieve JSON (" + response.getStatusText()
                                + ")");
                          }
                    }
                  });
                } catch (RequestException e) {
                  displayError("Couldn't retrieve JSON");
                }   
            }
        });
    }
    
    private void initToggleAnchorIcon(Image icon) {
        icon.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                float l = (float) ((float)anchor_viewer.getTopWidget().getOffsetHeight())/((float)anchor_viewer.getOffsetHeight());
//              Window.alert(l + ".");
                if (l < 0.05) {
                    anchor_viewer.setSplitPosition("30%");
                }
                else {
                    if (l > 0.96) {
                        anchor_viewer.setSplitPosition("30%");
                    }
                    else {
                        anchor_viewer.setSplitPosition("0%");
                    }
                }
            }
        });
    }
    
    private void initToogleDiscussionIcon(Image toggle_discussion_icon_image) {
        toggle_discussion_icon_image.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                float pos = (float) ((float)hsplitpanel.getLeftWidget().getOffsetWidth())/((float)hsplitpanel.getOffsetWidth());
                if (pos > 0.99) {
                    hsplitpanel.setSplitPosition("70%");
                }
                else {
                    hsplitpanel.setSplitPosition("100%");
                }
            }
        });
    }
    
    private void initGoToCCommon(Image go_to_classcommon_icon_image) {
    	go_to_classcommon_icon_image.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
            	openNewWindow("./ClassCommons.html?cid=" + cls_id + "&cname=" + cname);
            }
        });
    }
    
    public void initLogoutIcon(Image logout_icon) {
        logout_icon.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (user.getUid().indexOf("gmail") > -1) {
                    preLogoutGoogle();
                    
                    Window.alert("Google logout");
                }
                else {
                    if (user.getUid().indexOf("yahoo") > -1) {
                        preLogoutYahoo();
                        Window.alert("Yahoo logout");
                    }
                }
            }
//            public void onClick(ClickEvent event) {
//                final GWTCPopupBox upload_box = new GWTCPopupBox(GWTCPopupBox.OPTION_ROUNDED_BLUE);
//                
//                final FormPanel uploader_form_panel = new FormPanel();
//                uploader_form_panel.setAction("http://cscl.ist.psu.edu:5678/classconversation/service/ForumService"); //need to change to the actual url that handles uploading
//                uploader_form_panel.setEncoding(FormPanel.ENCODING_MULTIPART);
//                uploader_form_panel.setMethod(FormPanel.METHOD_POST);
//                
//                CaptionPanel upload_caption_panel = new CaptionPanel("Make it a discussion topic in the class forum");
//                
//                final VerticalPanel upload_form_element_panel = new VerticalPanel();
//                upload_caption_panel.add(upload_form_element_panel);
//                uploader_form_panel.setWidget(upload_caption_panel);
//                
//                HorizontalPanel hpanel_0 = new HorizontalPanel();
//                Label forum_list_label = new Label("Add it to: ");
//                hpanel_0.add(forum_list_label);
//                
//                
//                
//                prepareDropdownList(cls_id);
//                forum_list.addChangeHandler(new ChangeHandler() {
//                    public void onChange(ChangeEvent event) {
//                        ListBox list = (ListBox) event.getSource();
//                        Window.alert(list.getValue(list.getSelectedIndex()));
//                    }
//                });
//                forum_list.setName("parent_id");
//                hpanel_0.add(forum_list);
//                
//                upload_form_element_panel.add(hpanel_0);
//                
//                HorizontalPanel hpanel_2 = new HorizontalPanel();
//                Label content_label = new Label("Content: ");
//                hpanel_2.add(content_label);
//                TextArea content_box = new TextArea();
//                content_box.setSize("300px", "100px");
//                content_box.setName("content");
//                content_box.setText("Great! it is working now");
//                hpanel_2.add(content_box);
//                upload_form_element_panel.add(hpanel_2);
//                
//                content_box.addFocusHandler(new FocusHandler() {
//                  public void onFocus(FocusEvent event) {
//                      TextArea box = (TextArea)event.getSource();
//                      String tmp_str = box.getText();
//                      if (tmp_str.equalsIgnoreCase("Enter content here.")) {
//                          box.setText("");
//                      }
//                      else {
//                          return;
//                      }
//                  }
//                });
//                  
//                content_box.addBlurHandler(new BlurHandler() {
//                  public void onBlur(BlurEvent event) {
//                      TextArea box = (TextArea)event.getSource();
//                          String tmp_str = box.getText();
//                          if (tmp_str.equalsIgnoreCase("Enter content here.") || tmp_str.trim().equalsIgnoreCase("")) {
//                              box.setText("Enter content here.");
//                          }
//                          else {
//                              return;
//                          }
//                  }
//                });
//                
//                
//                Hidden operator = new Hidden();
//                operator.setName("op");
//                operator.setValue("addAttachment");
//                upload_form_element_panel.add(operator);
//  
//                Hidden redirector = new Hidden();
//                redirector.setName("redirect");
//                redirector.setValue("null");
//                upload_form_element_panel.add(redirector);
//                
//                Hidden hidden_itype_name = new Hidden();
//                hidden_itype_name.setName("itype");
//                hidden_itype_name.setValue("0");
//                upload_form_element_panel.add(hidden_itype_name);
//                
//                Hidden hidden_user_name = new Hidden();
//                hidden_user_name.setName("uid");
//                hidden_user_name.setValue(user_id);
//                upload_form_element_panel.add(hidden_user_name);
//                
//                Hidden hidden_class_id = new Hidden();
//                hidden_class_id.setName("cls");
//                hidden_class_id.setValue(cls_id);
//                upload_form_element_panel.add(hidden_class_id);
//  
////                Hidden hidden_parent_id = new Hidden();
////                hidden_parent_id.setName("parent_id");
////                hidden_parent_id.setValue(forum_id);
////                upload_form_element_panel.add(hidden_parent_id);
//  
//                Hidden hidden_object_type = new Hidden();
//                hidden_object_type.setName("type");
//                hidden_object_type.setValue("1");
//                upload_form_element_panel.add(hidden_object_type);
//                
//                
//                
//                final FileUpload upload = new FileUpload() {
//                    {
//                        addDomHandler(new ChangeHandler() {
//  
//                            public void onChange(
//                                    ChangeEvent event) {
//                                FileUpload upload = (FileUpload)event.getSource();
//                                VerticalPanel upload_form_element_panel = (VerticalPanel) upload.getParent();
//                                int upload_idx = upload_form_element_panel.getWidgetIndex(upload);
//                                VerticalPanel file_list = (VerticalPanel) upload_form_element_panel.getWidget(upload_idx - 1);
//                                file_list.clear();
//                                String[] names = getFiles(((FileUpload)event.getSource()).getElement());
//                                for (int i = 0; i < names.length; i++) {
//                                    file_list.add(new Label(names[i]));
//                                }
//                            }
//                        }, ChangeEvent.getType());
//                    }
//                };
//                upload.setName("fname");
//                upload.getElement().setAttribute("multiple", "");
//                upload_form_element_panel.add(new VerticalPanel());
//                upload_form_element_panel.add(upload);
//                
//                
//             // Add a 'submit' button.
//                HTML submit_button = new HTML("<div>Submit<span/><div>");
//                submit_button.setStyleName("round-button");
//                submit_button.getElement().setId("round-button-g");
//                submit_button.addClickHandler(new ClickHandler() {
//                  public void onClick(ClickEvent event) {
//                      String[] names = getFiles(upload.getElement());
//                      if (names.length < 1) {
//                          Window.alert("No file is selected!");
//                          return;
//                      }
//                      for (int i = 0; i < names.length; i++) {
//                          if (!names[i].substring(names[i].lastIndexOf('.') + 1).equalsIgnoreCase("pdf")) {
////                              Window.alert("can't upload files not in pdf format");
////                              return;
//                          }
//                      }
//                      uploader_form_panel.submit();
//                  }
//                });
//                
//                HTML cancel_button = new HTML("<div>Cancel<span/><div>");
//                cancel_button.setStyleName("round-button");
//                cancel_button.getElement().setId("round-button-g");
//                cancel_button.addClickHandler(new ClickHandler() {
//                  public void onClick(ClickEvent event) {
//                      upload_box.hide();
//                  }
//                });
//                
//                HorizontalPanel submit_cancel_button_panel = new HorizontalPanel();
//                submit_cancel_button_panel.add(submit_button);
//                submit_cancel_button_panel.add(cancel_button);
//                upload_form_element_panel.add(submit_cancel_button_panel);
//  
//                // Add an event handler to the form.
//                uploader_form_panel.addSubmitHandler(new FormPanel.SubmitHandler() {
//                  public void onSubmit(SubmitEvent event) {
//                      String[] names = getFiles(upload.getElement());
//                      if (names.length < 1) {
//                          Window.alert("No file is selected!");
//                      }
//                  }
//                });
//                uploader_form_panel.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
//                  public void onSubmitComplete(SubmitCompleteEvent event) {
//                      upload_box.hide();
//                  }
//                });
//                
//
//                upload_box.add(uploader_form_panel);
//
//                int X_ = calculateXposition(event.getNativeEvent().getClientX(), Window.getClientWidth(), 200);
//                int Y_ = calculateYposition(event.getNativeEvent().getClientY(), Window.getClientHeight(), 100);
//                if (event.getNativeEvent().getClientY() + 200 > Window.getClientHeight()) {
//                    upload_box.setPopupPosition(X_, Y_);
//                }
//                else {
//                    upload_box.setPopupPosition(X_, Y_);
//                }
//                upload_box.setZIndex(9999);
//                upload_box.show();
//            
//            }
        });
    }
    
    protected void prepareDropdownList(String cls_id) {
        String url = "http://cscl.ist.psu.edu:5678/classconversation/service/ForumService";
        String postData = "op=gforums&t=0&o=time asc&cls=" + cls_id;
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
        builder.setHeader("Content-type", "application/x-www-form-urlencoded");
        try {
          Request request = builder.sendRequest(postData, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              displayError("Couldn't retrieve JSON");
            }

            public void onResponseReceived(Request request, Response response) {
                  if (200 == response.getStatusCode()) {
                      forum_list.clear();
                      forum_list.addItem("Select...", "unselected");
                      JsArray<CommonObject> forums = asArrayOfCommonObject(response.getText());
                      CommonObject forum;
                      for (int i = 0; i < forums.length(); i++) { 
                          forum = forums.get(i);
                          forum_list.addItem(forum.getContent(), forum.getId());
//                          forum_list.addItem("The dark Knight", "1");
//                          forum_list.addItem("Batman begins", "2");
//                          forum_list.addItem("Hello", "3");
                      }
                  } else {
                    displayError("Error!");
                  }
            }
          });
        } catch (RequestException e) {
          displayError("Couldn't retrieve JSON");
        }
    }

    protected void displayError(String string) {
    }

//    public void filterHash() {
//      String hash = Window.Location.getHash();
//      if (!hash.equalsIgnoreCase(recorded_hash)) {
//          recorded_hash = hash;
//          cls_id = Window.Location.getParameter("cls");
//          if (cls_id.trim().length() > 4) { 
//              if ((discussion_id = Window.Location.getHash()).trim().length() > 5)  
//                  initForumPanel(discussion_id);
//              else initForumEntry(cls_id);
//          }
//      }
//      else {
//          recorded_hash = hash;
//      }
//  }
    
    public void loadForum(String id) {
        forum_id = id;
        String url = URL.encode("http://cscl.ist.psu.edu:5678/classconversation/service/ForumService");
        String postData = "op=goc&t=1&o=time desc&fid=" + id;
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
        builder.setHeader("Content-type", "application/x-www-form-urlencoded");
        try {
          Request request = builder.sendRequest(postData, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              displayError("Couldn't retrieve JSON");
            }

            public void onResponseReceived(Request request, Response response) {    
                if (200 == response.getStatusCode())    
                  {
                    JsArray<CommonObject> forums = asArrayOfCommonObject(response.getText());
                    CommonObject forum;
                    CommonObject discussion;
                    JsArray<CommonObject> discussions;
                    if (forums.length() > 0) {
                        forum = forums.get(0);
                        forum_name.setText(forum.getContent());
                        discussions = forum.getItems();
                        if (discussions != null && discussions.length() > 0) {
                            discussion = discussions.get(0);
                            loadDiscussion(discussion.getId());
                        }
                        else {
                            Window.alert("There is no discussion created under this fourm.");
                            loadEmptyDiscussion();
                        }
                    }
                  }
                  else 
                  {
                    displayError("Couldn't retrieve JSON (" + response.getStatusText()
                        + ")");
                  }
            }
          });
        } catch (RequestException e) {
          displayError("Couldn't retrieve JSON");
        }   
    }
    
    public int calculateXposition(int mouse_x, int window_width, int object_width){
        if (mouse_x + object_width > window_width) {
            return mouse_x - object_width;
        }
        else {
            return mouse_x;
        }
    }
    
    public int calculateYposition(int mouse_y, int window_heigth, int object_heigth){
        if (mouse_y + object_heigth > window_heigth) {
            return mouse_y - object_heigth;
        }
        else {
            return mouse_y;
        }
    }
    
    private void getUserOpenID(){
        // Initialize the service proxy.
        if (loginServiceSvc == null) {
            loginServiceSvc = GWT.create(LoginService.class);
        }
        
        // Set up the callback object.
        AsyncCallback<String> callback = new AsyncCallback<String>() {
            public void onFailure(Throwable caught) {
                caught.printStackTrace();
                
            }
            
            public void onSuccess(String result) {
                open_id = result.substring(0, result.indexOf(".NOTACTIVATED"));
                user_id = open_id;
            }
        };
        loginServiceSvc.getUserOpenId(callback);
    }
    
    private void loginFromSession(){
        // Initialize the service proxy.
        if (loginServiceSvc == null) {
            loginServiceSvc = GWT.create(LoginService.class);
        }
        // Set up the callback object.
        AsyncCallback<User> callback = new AsyncCallback<User>() {
            public void onFailure(Throwable caught) {
                caught.printStackTrace();
            }

            public void onSuccess(User u) {
                user = u;
                
                if (u == null){
                    Window.Location.replace("http://cscllab.ist.psu.edu");
                }
                else{
//                    Window.alert(user.getFName());
                	open_id = user.getUid();
                	user_id = open_id;
                    postLogin();
                    Log.debug(user.getFullName() +" comes in!");
//                    getCid(cname);
                }
            }
        };
        loginServiceSvc.loginFromSession(callback);
    }
    
    private void preLogoutGoogle() {
        String url = URL.encode("http://cscl.ist.psu.edu:5678/classconversation/service/LoginServlet?op=logout");
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
        builder.setHeader("Content-type", "application/x-www-form-urlencoded");
        try {
          Request request = builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              displayError("Couldn't connect with server");
            }

            public void onResponseReceived(Request request, Response response) {
              if (200 == response.getStatusCode()) { 
//                  redirect(GWT.getModuleBaseURL()+"../forum.html");
                  redirect("https://www.google.com/accounts/Logout");
              } else {
                displayError("Couldn't retrieve JSON (" + response.getStatusText()
                    + ")");
              }
            }
          });
        } catch (RequestException e) {
          displayError("Couldn't retrieve JSON");
        }
    }
    
    private void preLogoutYahoo() {
        String url = URL.encode("http://cscl.ist.psu.edu:5678/classconversation/service/LoginServlet?op=logout");
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
        builder.setHeader("Content-type", "application/x-www-form-urlencoded");
        try {
          Request request = builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              displayError("Couldn't connect with server");
            }

            public void onResponseReceived(Request request, Response response) {
              if (200 == response.getStatusCode()) { 
//                  redirect(GWT.getModuleBaseURL()+"../forum.html");
                  redirect("https://login.yahoo.com/config/login?logout=1");
              } else {
                displayError("Couldn't retrieve JSON (" + response.getStatusText()
                    + ")");
              }
            }
          });
        } catch (RequestException e) {
          displayError("Couldn't retrieve JSON");
        }
    }
    
    native void openNewWindow(String url)
    /*-{
    	var tmpstr = url + ",'target=_blank'";
            $wnd.open(url);

    }-*/; 
    
    native void redirect(String url)
    /*-{
            $wnd.location.replace(url);

    }-*/; 
    
    private final native JsArray<CommonObject> asArrayOfCommonObject(String json) /*-{
        return eval(json);
    }-*/;
    
    public native String[] getFiles(Element upload) /*-{
        var input = upload;
        var names = new Array();       
               for (var i = 0; i < input.files.length; i++) {
               names[i] = input.files[i].name;
    //            $wnd.alert(input.files[i].name);
               }
        return names;
    }-*/;
    
    private native String replaceURLWithHTMLLinks(String text) /*-{
        var replaceText, replacePattern1, replacePattern2, replacePattern3;
    
        //URLs starting with http://, https://, or ftp://
        replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
        replacedText = text.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
    
        //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
        replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
        replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
    
        //Change email addresses to mailto:: links.
        replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
        replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
        //alert(replacedText);
        return replacedText
    }-*/;
    
    public static native String isInputInvalid(String regx, String subject)/*-{
        var patt1=/(\\{1,})/gi;
        var rs = subject.match(patt1);
        var is_invalid = "false";
        if (rs == null || rs.length == 0) {
            return "false";
        } else {
            for (i = 0; i < rs.length; i++) {
                if (rs[i].length % 2) {
                    is_invalid = "true";
                }
                else {
                }
            }
            return is_invalid;
        }
    }-*/;
    
    public static native String getReturnID(String str)/*-{
        var patt1 = />(.*?)<\//;
        var temp = str.match(patt1);
        return temp[1];
    }-*/;
    
    public static native String replaceDiscussionID(String str, String id)/*-{
        var patt1 = /\/[a-zA-Z0-9_-]+/gi;
        var text = str.replace(patt1, "/" + id);
        return text;
    }-*/;
    
    public static native String getScreenHeight() /*-{
        var screenHeight = screen.availHeight + "";
        return screenHeight;
    }-*/;
    
    public static native String getScreenWidth() /*-{
        var screenWidth = screen.availWidth + "";
        return screenWidth;
    }-*/;
    
//    native void addHashUpdateListener(CCForum ccforum) /*-{
//      $wnd.addEventListener('hashchange', function(){
//          ccforum.@edu.psu.hci.classconversation.client.CCForum::filterHash()();
//      });
//  }-*/;
}
